package com.interview.rtc.aigc.config;

import com.interview.rtc.aigc.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtFilter.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String path = request.getRequestURI();

        logger.debug("处理请求: {}", path);

        // 不需要验证的路径
        if (path.contains("/api/user/login") ||
            path.contains("/api/user/register") ||
            path.contains("/api/user/send-code") ||
            path.contains("/api/user/verify-code") ||
            path.contains("/api/chat-history/list/public") ||
            path.contains("/api/aigc") ) {
            logger.debug("路径 {} 不需要验证", path);
            filterChain.doFilter(request, response);
            return;
        }

        // 获取Authorization头
        final String header = request.getHeader("Authorization");
        logger.debug("Authorization头: {}", header);

        // 检查是否有token
        if (header != null && header.startsWith("Bearer ")) {
            // 提取token
            String token = header.substring(7);

            try {
                // 验证token
                if (StringUtils.hasText(token) && jwtTokenUtil.validateToken(token)) {
                    // 从token中获取用户信息
                    Long userId = jwtTokenUtil.getUserIdFromToken(token);
                    logger.debug("验证token成功, 用户ID: {}", userId);

                    // 将用户ID设置到请求属性中，以便控制器使用
                    request.setAttribute("userId", userId);

                    // 继续处理请求
                    filterChain.doFilter(request, response);
                    return;
                } else {
                    logger.warn("无效的token: {}", token);
                }
            } catch (Exception e) {
                // token解析或验证出错
                logger.error("JWT验证失败: {}", e.getMessage(), e);
            }
        } else {
            logger.info("没有提供Authorization头或格式不正确");
        }

        // 对于需要token但没有提供有效token的请求，返回401错误
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401,\"message\":\"未授权:无效的token\"}");
    }
}
